package qs.openxt.libs.splashscreen;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import qs.openxt.libs.App;
import qs.openxt.libs.R;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.AlbumUtil;
import qs.openxt.libs.util.MResource;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016/5/17.
 */
public class SplashScreenPage implements ViewPager.OnPageChangeListener, View.OnClickListener {
    private Context context;
    private Dialog dialog = null;
    private ViewPager viewPager = null;
    private List<View> mList = null;
    private MyPagerAdapter vpAdapter = null;
    private int resourceId;
    private String CanSkip = "true";//能否跳过
    private String Mode = null;//切换方式
    private String ExpiryDate = null;//有效期 默认的图片还是现在的那张。 当获取到新版的图片之后，获取到新的图片之后显示新图片。获取到的图片会有有效期，超过有效期显示默认的
    private Date $ExpiryDate = null;
    private String IsWait = "true"; //是否显示待加载页面
    private String ChangeDefault = "false";//是否修改默认图
    private JSONArray IMGS = null;
    private Button btn_skip = null;
    private RelativeLayout default_splashscreen_001 = null, default_splashscreen_002 = null;

    public SplashScreenPage(Context context, int resourceId){
        this.context = context;
        this.resourceId = resourceId;
    }

    public void loadPage(){
        try {
            JSONObject config = null;
            String _config = Utils.getLocalStorage(context, App.SPLASHSCREEN);
            if (StringUtil.isNull(_config))
                config = new JSONObject();
            else
                config = JSON.parseObject(_config);

            String isFirstIn = Utils.getLocalStorage(context, App.SPLASHSCREEN_ISFIRST);
            if(StringUtil.isNull(isFirstIn))
                isFirstIn = "true";
            IMGS = config.getJSONArray("IMGS");
            if(IMGS == null)
                IMGS = new JSONArray();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            CanSkip = config.getString("CanSkip");//能否跳过
            Mode = config.getString("Mode");//切换方式
            ExpiryDate = config.getString("ExpiryDate");//有效期 默认的图片还是现在的那张。 当获取到新版的图片之后，获取到新的图片之后显示新图片。获取到的图片会有有效期，超过有效期显示默认的
            if(!StringUtil.isNull(ExpiryDate)){
                $ExpiryDate = dateFormat.parse(ExpiryDate);
            }
            IsWait = config.getString("IsWait"); //是否显示待加载页面
            ChangeDefault = config.getString("ChangeDefault");//是否修改默认图
            boolean isShow = (null == $ExpiryDate ? ("true".equals(isFirstIn) ? true : false) : true);
            View splashscreen = LayoutInflater.from(context).inflate(R.layout.splashscreen, null);
            boolean showDialog = false;
            //是否显示切换页
            if(IMGS.size() > 0 && isShow) {
                //判断时间有效期
                if(null != $ExpiryDate) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime($ExpiryDate);
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    if(new Date().getTime() < calendar.getTime().getTime()){
                        showDialog = true;
                        for (int i = 0, j = IMGS.size(); i < j; i++) {
                            String path = IMGS.getString(i);
                            if(!new File(path).exists()){
                                showDialog = false;
                            }
                        }
                        if(showDialog)
                            showSwitchPage(splashscreen);
                    }
                }else{
                    showDialog = true;
                    showSwitchPage(splashscreen);
                }
            }

            if("true".equals(IsWait)) {
                showDialog = true;
                showWaitPage(splashscreen);
            }

            if(!showDialog)
                return;

            dialog = new Dialog(context, android.R.style.Theme_Translucent_NoTitleBar);
            if ((((Activity) context).getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager.LayoutParams.FLAG_FULLSCREEN) {
                dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
            dialog.getWindow().setWindowAnimations(R.style.dialogWindowAnim);
            dialog.setContentView(splashscreen);
            dialog.setCancelable(false);
            dialog.show();
        }catch (Exception e){

        }
    }

    private void showSwitchPage(View splashscreen){
        btn_skip = (Button) splashscreen.findViewById(R.id.btn_skip);
        viewPager = (ViewPager) splashscreen.findViewById(R.id.viewpager);
        viewPager.setVisibility(View.VISIBLE);
        if ("true".equals(CanSkip)) {
            btn_skip.setVisibility(View.VISIBLE);
            btn_skip.setOnClickListener(this);
        }

        mList = new ArrayList<View>();
        for (int i = 0, j = IMGS.size(); i < j; i++) {
            String path = IMGS.getString(i);
            ImageView imageView = new ImageView(context);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setImageURI(AlbumUtil.getImageContentUri(context, new File(path)));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            if(i == j - 1){
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        closePage();
                    }
                });
            }

            mList.add(imageView);
        }

        // 初始化Adapter
        vpAdapter = new MyPagerAdapter(mList, context);
        viewPager.setAdapter(vpAdapter);
        // 绑定回调
        viewPager.setOnPageChangeListener(this);
    }

    private void showWaitPage(View splashscreen){
        default_splashscreen_001 = (RelativeLayout) splashscreen.findViewById(R.id.default_splashscreen_001);
        default_splashscreen_001.setVisibility(View.VISIBLE);
        default_splashscreen_002 = (RelativeLayout) splashscreen.findViewById(R.id.default_splashscreen_002);
        default_splashscreen_002.setVisibility(View.VISIBLE);
        //是否显示待加载页面
        TextView textView = (TextView) splashscreen.findViewById(R.id.tv_version);
        String version = "版本号 : " + ActivityUtil.getVersion(context);
        textView.setText(version);

        ImageView imgView = (ImageView) splashscreen.findViewById(R.id.start_page_img);
        if ("true".equals(ChangeDefault))
            imgView.setImageURI(AlbumUtil.getImageContentUri(context, new File(IMGS.getString(0))));
        else
            imgView.setBackgroundResource(MResource.getIdByName(context, "mipmap", "page"));

        ImageView loadingImage = (ImageView) splashscreen.findViewById(R.id.iv_loading0);
        if (loadingImage.getBackground() instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) loadingImage.getBackground();
            animationDrawable.start();
        }
    }

    public void close(){
        if(dialog == null)
            return;

        if (default_splashscreen_001 != null) {
            default_splashscreen_001.setVisibility(View.GONE);
        }
        if (default_splashscreen_002 != null) {
            default_splashscreen_002.setVisibility(View.GONE);
        }
        if(viewPager == null || (viewPager != null && viewPager.getVisibility() == View.GONE))
            dialog.dismiss();

        Utils.setLocalStorage(context, App.SPLASHSCREEN_ISFIRST, "false");
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_skip){
            closePage();
        }
    }

    private void closePage(){
        btn_skip.setVisibility(View.GONE);
        viewPager.setVisibility(View.GONE);
        if(default_splashscreen_001 == null)
            close();

        if(default_splashscreen_001 != null && default_splashscreen_001.getVisibility() == View.GONE)
            close();
    }
}
